<?php

declare(strict_types=1);

use App\ApplicationParams;
use Yiisoft\Aliases\Aliases;
use Yiisoft\DataResponse\DataResponseFactory;
use Yiisoft\DataResponse\DataResponseFactoryInterface;
use Yiisoft\DataResponse\DataResponseFormatterInterface;
use Yiisoft\DataResponse\Formatter\JsonDataResponseFormatter;

/** @var array $params */

return [
    ApplicationParams::class => [
        '__construct()' => [
            'name' => $params['application']['name'],
            'charset' => $params['application']['charset'],
            'locale' => $params['application']['locale'],
        ],
    ],
    DataResponseFactoryInterface::class => DataResponseFactory::class,
    DataResponseFormatterInterface::class => JsonDataResponseFormatter::class,
    \PDO::class => static function (Aliases $aliases): \PDO {
        $defaultDsn = 'pgsql:host=192.168.1.105;port=5432;dbname=ez6_lan_yii3';
        $dsn = (string) (getenv('APP_DB_DSN') ?: $defaultDsn);
        $username = (string) (getenv('APP_DB_USER') ?: 'ezsoft6');
        $password = (string) (getenv('APP_DB_PASSWORD') ?: 'Ez4006400159');

        try {
            $pdo = new \PDO($dsn, $username, $password);
        } catch (\PDOException $exception) {
            throw new \RuntimeException(
                sprintf('Failed to connect to PostgreSQL using DSN "%s": %s', $dsn, $exception->getMessage()),
                previous: $exception,
            );
        }

        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);

        return $pdo;
    },
];
